package com.j.lemon.learn.thread.ThreadControl;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Author lijunjun
 * @Date 2019-04-02 10:43
 * @Description Object.wait(),Object.notify() ,可以实现两个线程交替执行,wait 和 notify只能在synchronize代码块中使用，
 *              wait 和 notify 是 object 类的方法，wait会释放当前锁，直到这个对象(被锁住的对象)调用了notify方法。下面是交替打印的一个例子
 */
public class AlternatePrinting {
    private static volatile int num;

    public static void main(String[] args) {
        Object object = new Object();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(8,16,0, TimeUnit.MILLISECONDS,
                new LinkedBlockingDeque<>(),r ->(new Thread(r,r.toString()+"haha")),new ThreadPoolExecutor.DiscardPolicy());
        for (int i = 0; i < 2; i++) {
            threadPoolExecutor.execute(() -> {
                synchronized (object){
                    for (int j = 0; j < 100; j++) {
                        object.notify();
                        System.out.println(Thread.currentThread().getName()+"+1");
                        num++;
                        System.out.println("result:"+num);
                        try {
                            object.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
        }
        threadPoolExecutor.shutdown();
    }
}
